package experimentSecond;

import java.util.*;

public class jobScheduling {

    public static void main(String[] args) {

        // 创建作业列表
        Job[] jobs = new Job[]{
                new Job("Job1", 0, 4),
                new Job("Job2", 1, 2),
                new Job("Job3", 3, 6),
                new Job("Job4", 9, 33),
                new Job("Job5", 12, 4)
        };

        // FCFS 调度
        System.out.println("先来先服务（FCFS）调度结果：");
        FCFS(jobs.clone());

        // SJF 调度
        System.out.println("最短作业优先（SJF）调度结果：");
        SJF(jobs.clone());

        System.out.println("响应比高者优先（HRN）的调度结果");
        HRNScheduler hrnScheduler = new HRNScheduler();
        hrnScheduler.addJobs(jobs);
        hrnScheduler.schedule();
    }


    //先来先服务
    public static void FCFS(Job[] jobs){
        int currentTime = 0;
        for(Job job : jobs){
            if(job.arrivalTime > currentTime){
                currentTime = job.arrivalTime;
            }
            currentTime += job.burstTime;
            job.finishTime = currentTime;
            job.printJobInfo();
        }
    }

    //短作业优先
    public static void SJF(Job[] jobs) {
        int currentTime = 0;
        ArrayList<Job> jobList = new ArrayList<>(Arrays.asList(jobs));
        // 定义一个优先级队列，优先级为 burstTime，burstTime 小的先执行
        PriorityQueue<Job> queue = new PriorityQueue<>(Comparator.comparingInt(job -> job.burstTime));

        while (!jobList.isEmpty() || !queue.isEmpty()) {
            // 将所有到达的作业都添加到优先级队列中
            int finalCurrentTime = currentTime;
            jobList.removeIf(job -> {
                if (job.arrivalTime <= finalCurrentTime) {
                    queue.offer(job);
                    return true;
                }
                return false;
            });

            if (!queue.isEmpty()) {
                // 从队列中取得作业并执行
                Job nextJob = queue.poll();
                currentTime += nextJob.burstTime;
                nextJob.finishTime = currentTime;
                nextJob.printJobInfo();
            } else {
                // 如果没有作业可以执行，那么将时间向前移动到下一个作业的到达时间
                currentTime = jobList.get(0).arrivalTime;
            }
        }
    }
}
